import React from 'react';
import { Settings as LayoutSettings, MenuDataItem } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import { notification, message } from 'antd';
import { history, RequestConfig, RunTimeLayoutConfig } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { ResponseError } from 'umi-request';
import { queryCurrent, queryMenuData } from './services/user';
import defaultSettings from '../config/defaultSettings';
import {
  SmileOutlined,
  HeartOutlined,
  CrownOutlined,
  KeyOutlined,
  ExperimentOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import routes from '../config/routes';

const IconMap = {
  smile: <SmileOutlined />,
  heart: <HeartOutlined />,
  crown: <CrownOutlined />,
  key: <KeyOutlined />,
  setting: <SettingOutlined />,
  experiment: <ExperimentOutlined />,
};

/**
 * 获取用户信息比较慢的时候会展示一个 loading
 */
export const initialStateConfig = {
  loading: <PageLoading />,
};

const fetchUserInfo = async () => {
  try {
    const r = await queryCurrent();
    return r.data;
  } catch (error) {
    history.push('/user/login');
  }
  return undefined;
};

/**
 * 获取全部菜单数据(包含操作)
 * @returns 
 */
const getAllMenuData = async () => {
  try {
    const r = await queryMenuData();
    const menuOperateData = r.data;
    const menuData = loopMenuItem(JSON.parse(JSON.stringify(menuOperateData)));
    return {
      menuOperateData,
      menuData
    };
  } catch (error) {
    history.push('/user/login');
  }
  return undefined;
};

const loopMenuItem = (menus: MenuDataItem[]): MenuDataItem[] => {
  return menus.filter(item => {
    return item.genre == 'directory' ? true : false;
  }).map(({ icon, children, ...item }) => {
    return ({
      ...item,
      path: item.path || '/',
      key: item.id,
      icon: breadthFirstSearchIcon(item.path),
      children: children && loopMenuItem(children),
    })
  });
}

const breadthFirstSearchIcon = (path: any) => {
  for (let route of routes) {
    let queue = [];
    queue.unshift(route);
    while (queue.length != 0) {
      let item: any = queue.shift();
      if (item.icon != null && item.path == path) {
        return IconMap[item.icon as string];
      }
      let children = item.routes;
      if (children) {
        for (let i = 0; i < children.length; i++) {
          queue.push(children[i]);
        }
      }
    }
  }
  return null;
};

export async function getInitialState(): Promise<{
  settings?: LayoutSettings;
  currentUser?: API.CurrentUser;
  menuData?: object;
  menuOperateData?: object;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  getAllMenuData?: () => Promise<any | undefined>;
}> {
  const currentUser = await fetchUserInfo();
  const allMenuData = await getAllMenuData();
  const menuData = allMenuData?.menuData;
  const menuOperateData = allMenuData?.menuOperateData;

  return {
    settings: defaultSettings,
    currentUser,
    menuData,
    menuOperateData,
    fetchUserInfo,
    getAllMenuData,
  };
}

export const layout: RunTimeLayoutConfig = ({ initialState }: any) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      const { currentUser } = initialState;
      // 如果没有登录，重定向到 login
      if (!currentUser && location.pathname !== '/user/login') {
        console.log('用户信息为空跳转到登录页');
        history.push('/user/login');
      }
    },
    menuHeaderRender: undefined,
    menuDataRender: (menuData) => initialState.menuData || menuData,
    ...initialState?.settings,
  };
};

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '该请求需登录才能访问。',
  403: '用户未得到授权，访问被禁止。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  405: '请求方法不被允许。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

enum ErrorShowType {
  SILENT = 0,
  WARN_MESSAGE = 1,
  ERROR_MESSAGE = 2,
  NOTIFICATION = 4,
  REDIRECT = 9,
}

interface ErrorInfoStructure {
  success: boolean;
  data?: any;
  errorCode?: string;
  errorMessage?: string;
  showType?: ErrorShowType;
  traceId?: string;
  host?: string;
  [key: string]: any;
}

/**
 * 异常处理程序
 */
const errorHandler = (error: ResponseError) => {
  const { response } = error;
  if (response && response.status) {
    if (response.status == 401) {
      history.push('/user/login');
    }
    let errorInfo: ErrorInfoStructure | undefined;
    errorInfo = error.data;
    const { status, url } = response;

    if (errorInfo) {
      const errorMessage = errorInfo?.errorMessage;
      switch (errorInfo?.showType) {
        case ErrorShowType.SILENT:
          // do nothing
          break;
        case ErrorShowType.WARN_MESSAGE:
          message.warn(errorMessage);
          break;
        case ErrorShowType.ERROR_MESSAGE:
          message.error(errorMessage);
          break;
        case ErrorShowType.NOTIFICATION:
          notification.error({
            message: `请求错误 ${status}: ${url}`,
            description: errorMessage,
          });
          break;
        default:
          message.error(errorMessage);
          break;
      }
    } else {
      message.error(error.message || '请求错误，请重试。');
    }
  }

  if (!response) {
    notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常',
    });
  }
  throw error;
};

export const request: RequestConfig = {
  errorHandler,
};
